<?php
	require_once(dirname(__FILE__).'/../shared/database.php');

	$mb_url = "http://musicbrainz.org/ws/1/artist/?type=xml&query=sortname:";
	
	$results = Database::instance()->query("SELECT * FROM items WHERE id LIKE 'GROVE_%'");
	
	$count = 0;
	echo "[\n";
	
	while($row = mysql_fetch_assoc($results))
	{
		$name = $row['label'];
		$processed_name = preg_replace("/\(.*?\)/", "", $name);
		
		// $parts = explode(',', $processed_name);
		// 
		// $surname = array_shift($parts);
		// $processed_name = trim(implode(" ", $parts)." $surname");
		
		$processed_name = preg_replace("/\s+/", " ", $processed_name);
		
		$search_url = $mb_url.'"'.urlencode($processed_name).'"';
		$search_xml = file_get_contents($search_url);
		//echo "$search_url\n";

		$metadata = simplexml_load_string($search_xml);
		
		if($metadata->{"artist-list"})
		{
			$artist = $metadata->{"artist-list"}->artist[0];
			
			$ext_attr = $artist->attributes("http://musicbrainz.org/ns/ext-1.0#");
			
			//echo "$processed_name\t => ".$artist->{"sort-name"}." (".$ext_attr['score'].")\n";
			
			// var_dump($order_name);
			// var_dump($ext_attr);
			// var_dump($artist);
			
			$json = array(
				"id" => $artist->attributes()->id."",
				"label" => $artist->{"sort-name"}."",
				"metadata" => array(
					"Info" => "http://musicbrainz.org/artist/".$artist->attributes()->id,
					"X0" => "MusicBrainz",
				),
			);
			
			if($artist->{"life-span"})
			{
				$lifespan = $artist->{"life-span"}->attributes();
				
				$bd = $dd = "0000-00-00";
				
				if($lifespan->begin)
					$bd = $lifespan->begin."";
					
				if($lifespan->end)
					$dd = $lifespan->end."";
				
				$json['metadata']['Birth_Date'] = $bd;
				$json['metadata']['Death_Date'] = $dd;
			}
			
			if($count > 0)
				echo "\n,";
				
			echo json_encode($json);
			
			$count++;
		}
		
		sleep(2);
	}
	
	echo "]\n";
?>